import type { App } from 'vue'
import type {
  LanguageType,
  UseModuleType,
  WritingMode,
} from '../../enums'
import { useTitle } from '@vueuse/core'
import { ElMessageBox } from 'element-plus'
import {
  cloneDeep,
  isEqual,
  omit,
} from 'lodash-es'
import { AppCodeType } from '../../enums'
import {
  $t,
  i18n,
} from '../../modules/i18n'
import {
  DEFAULT_LANGUAGE,
  THEME_COLOR,
  TITLE,
  WRITING_MODE,
} from '../../settings'
import useAppStore from '../../store/app'
import useConfigStore from '../../store/config'
import useLocaleStore from '../../store/locale'
import useProjectStore from '../../store/project'
import { useToggleTheme } from './theme'

// @unocss-include
function data() {
  return [
    {
      type: -1,
      name: $t('商户端'),
      code: '1111111111',
      active: true,
      sort: 1,
      children: [
        {
          type: 1,
          name: $t('权限中心'),
          code: 'auth',
          active: true,
          sort: 1,
          children: [
            {
              type: 2,
              name: $t('首页'),
              code: '1111111111_auth__home',
              icon: 'carbon-home',
              path: '/home',
              component: '/home/index.vue',
              flag: 'New',
              flagColor: '#ff6f91',
              visible: true,
              // fullscreen: true,
              children: [],
              meta: {
                title: '权限中心-首页',
              },
            },
            {
              type: 2,
              name: $t('canvas-test'),
              code: 'auth__canvas',
              icon: 'carbon-home',
              path: '/canvas-test',
              component: '/canvas-test/index.vue',
              flag: 'New',
              flagColor: '#ff6f91',
              visible: true,
              fullscreen: false,
              href: '',
              children: [],
              meta: {
                title: '权限中心-canvas',
              },
            },
            {
              type: 2,
              name: $t('外链测试'),
              code: '1111111111_auth__link',
              icon: 'carbon-home',
              href: 'https://www.baidu.com',
              // path: '/home',
              // component: '/home/index.vue',
              visible: true,
              // fullscreen: true,
              children: [],
              meta: {
                // title: '权限中心-首页',
              },
            },
            {
              type: 2,
              name: $t('iframe测试'),
              code: 'auth__iframe',
              icon: 'carbon-home',
              path: '/iframe/test',
              // component: '/home/index.vue',
              visible: true,
              fullscreen: false,
              href: '',
              iframeSrc: 'https://element-plus.org/zh-CN/guide/design.html',
              children: [],
              meta: {
                title: '权限中心-首页',
              },
            },
            {
              type: 2,
              name: $t('项目管理'),
              code: '1111111111_auth__project',
              icon: 'carbon-home',
              flag: 'Hot',
              flagColor: '#ff9671',
              // path: '/project-admin',
              // component: '/project-admin/index.vue',
              visible: true,
              // fullscreen: true,
              // meta: {
              //   title: '权限中心-项目管理',
              // },
              children: [],
            },
            {
              type: 2,
              name: $t('应用管理'),
              code: '1111111111_auth__app',
              icon: 'carbon-home',
              path: '/app-admin',
              component: '/app-admin/index.vue',
              href: '',
              visible: true,
              meta: {
                title: '权限中心-应用管理',
              },
              children: [
                {
                  type: 2,
                  name: $t('应用管理__详情页'),
                  code: '1111111111_auth__app__detail',
                  path: '/app-admin/detail',
                  component: '/app-admin/pages/detail.vue',
                  href: '',
                  visible: false,
                },
                {
                  type: 2,
                  name: $t('应用管理__anchor'),
                  code: '1111111111_auth__app__anchor',
                  path: '/app-admin/anchor',
                  component: '/app-admin/pages/anchor.vue',
                  href: '',
                  visible: false,
                },
                {
                  type: 3,
                  name: $t('新增'),
                  code: '1111111111_auth__app__add',
                },
              ],
            },
            {
              type: 2,
              name: $t('菜单管理'),
              code: '1111111111_auth__menu',
              icon: 'carbon-home',
              path: '/menu-admin',
              component: '/menu-admin/index.vue',
              href: '',
              visible: true,
              // defaultShow: true,
              meta: {
                title: '权限中心-菜单管理',
              },
              children: [],
            },
            {
              type: 2,
              name: $t('租户管理'),
              code: '1111111111_auth__tenant',
              icon: 'carbon-home',
              path: '/tenant-admin',
              component: '/tenant-admin/index.vue',
              href: '',
              visible: true,
              // defaultShow: true,
              meta: {
                title: '权限中心-租户管理',
              },
              children: [],
            },
            {
              type: 2,
              name: $t('用户管理'),
              code: '1111111111_auth__user',
              icon: 'carbon-home',
              path: '/user-admin',
              component: '/user-admin/index.vue',
              href: '',
              visible: true,
              // defaultShow: true,
              meta: {
                title: '权限中心-用户管理',
              },
              children: [],
            },
          ],
        },
        {
          type: 1,
          name: $t('配置中心'),
          code: 'config',
          active: false,
          sort: 2,
          children: [
            {
              type: 2,
              name: $t('首页'),
              code: '1111111111_config_home',
              icon: 'carbon-home',
              path: '/home',
              component: '/home/index.vue',
              href: '',
              visible: true,
              meta: {
                title: '配置中心-首页',
              },
              children: [],
            },
          ],
        },
        {
          type: 1,
          name: $t('翻译中心'),
          code: 'translate',
          active: false,
          sort: 2,
          children: [
            {
              type: 2,
              name: $t('首页'),
              code: '1111111111_translate_home',
              icon: 'carbon-home',
              path: '/home',
              component: '/home/index.vue',
              href: '',
              visible: true,
              meta: {
                title: '翻译中心-首页',
              },
              children: [],
            },
          ],
        },
      ],
    },
    {
      type: -1,
      name: $t('工厂端'),
      code: '2222222',
      active: false,
      sort: 1,
      children: [
        {
          type: 1,
          name: $t('配置中心'),
          code: 'config',
          // port: '6062',
          active: true,
          sort: 2,
          children: [
            {
              type: 2,
              name: $t('首页'),
              code: '2222222_config_home',
              icon: 'carbon-home',
              path: '/home',
              component: '/home/index.vue',
              href: '',
              visible: true,
              meta: {
                title: '配置中心-首页',
              },
              children: [],
            },
          ],
        },

        {
          type: 1,
          name: $t('翻译中心'),
          code: 'translate',
          // port: '6063',
          active: false,
          sort: 2,
          children: [
            {
              type: 2,
              name: $t('首页'),
              code: '2222222_translate_home',
              icon: 'carbon-home',
              path: '/home',
              component: '/home/index.vue',
              href: '',
              visible: true,
              meta: {
                title: '翻译中心-首页',
              },
              children: [],
            },
          ],
        },
      ],
    },
    {
      type: -1,
      name: $t('运营端'),
      code: '33333333',
      active: false,
      sort: 1,
      children: [
        {
          type: 1,
          name: $t('翻译中心'),
          code: 'translate',
          // port: '6063',
          active: true,
          sort: 2,
          children: [
            {
              type: 2,
              name: $t('首页'),
              code: '33333333_translate_home',
              icon: 'carbon-home',
              path: '/home',
              component: '/home/index.vue',
              href: '',
              visible: true,
              meta: {
                title: '翻译中心-首页',
              },
              children: [],
            },
          ],
        },
      ],
    },
  ] as any
}

function getApps(type: AppCodeType) {
  return ({
    [AppCodeType.AUTH]: [{
      type: 1,
      name: $t('权限中心'),
      code: 'auth',
      active: true,
      sort: 1,
      children: [
        {
          type: 2,
          name: $t('首页'),
          code: 'auth__home',
          icon: 'carbon-home',
          path: '/home',
          component: '/home/index.vue',
          flag: 'New',
          flagColor: '#ff6f91',
          visible: true,
          fullscreen: false,
          href: '',
          children: [],
          meta: {
            title: '权限中心-首页',
          },
        },
        {
          type: 2,
          name: $t('canvas-test'),
          code: 'auth__canvas',
          icon: 'carbon-home',
          path: '/canvas-test',
          component: '/canvas-test/index.vue',
          flag: 'New',
          flagColor: '#ff6f91',
          visible: true,
          fullscreen: false,
          href: '',
          children: [],
          meta: {
            title: '权限中心-canvas',
          },
        },
        {
          type: 2,
          name: $t('tsx测试'),
          code: 'auth__tsx',
          icon: 'carbon-home',
          path: '/tsx-test',
          component: '/tsx-test/index.vue',
          flag: 'Hot',
          flagColor: '#ff6f91',
          visible: true,
          fullscreen: false,
          href: '',
          children: [],
          meta: {
            title: '权限中心-tsx',
          },
        },
        {
          type: 2,
          name: $t('外链测试'),
          code: '1111111111_auth__link',
          icon: 'carbon-home',
          href: 'https://www.baidu.com',
          // path: '/home',
          // component: '/home/index.vue',
          visible: true,
          // fullscreen: true,
          children: [],
          meta: {
            // title: '权限中心-首页',
          },
        },
        {
          type: 2,
          name: $t('iframe测试'),
          code: 'auth__iframe',
          icon: 'carbon-home',
          path: '/iframe/test',
          // component: '/home/index.vue',
          visible: true,
          fullscreen: false,
          href: '',
          iframeSrc: 'https://element-plus.org/zh-CN/guide/design.html',
          children: [],
          meta: {
            title: '权限中心-首页',
          },
        },
        {
          type: 2,
          name: $t('项目管理'),
          code: 'auth__project__1',
          icon: 'carbon-home',
          flag: 'Hot',
          flagColor: '#ff9671',
          // path: '/project-admin',
          // component: '/project-admin/index.vue',
          visible: true,
          // fullscreen: false,
          children: [],
          // meta: {
          //   title: '权限中心-项目管理',
          // },
        },
        {
          type: 2,
          name: $t('应用管理'),
          code: 'auth__app',
          icon: 'carbon-home',
          path: '/app-admin',
          component: '/app-admin/index.vue',
          href: '',
          visible: true,
          meta: {
            title: '权限中心-应用管理',
          },
          children: [
            {
              type: 2,
              name: $t('应用管理__详情页'),
              code: 'auth__app__detail',
              path: '/app-admin/detail',
              component: '/app-admin/pages/detail.vue',
              href: '',
              visible: false,
            },
            {
              type: 2,
              name: $t('应用管理__anchor'),
              code: 'auth__app__anchor',
              path: '/app-admin/anchor',
              component: '/app-admin/pages/anchor.vue',
              href: '',
              visible: false,
            },
            {
              type: 3,
              name: $t('新增'),
              code: 'auth__app__add',
            },
          ],
        },
        {
          type: 2,
          name: $t('菜单管理'),
          code: 'auth__menu',
          icon: 'carbon-home',
          path: '/menu-admin',
          component: '/menu-admin/index.vue',
          href: '',
          visible: true,
          // defaultShow: true,
          children: [],
          meta: {
            title: '权限中心-菜单管理',
          },
        },
        {
          type: 2,
          name: $t('租户管理'),
          code: '1111111111_auth__tenant',
          icon: 'carbon-home',
          path: '/tenant-admin',
          component: '/tenant-admin/index.vue',
          href: '',
          visible: true,
          // defaultShow: true,
          meta: {
            title: '权限中心-租户管理',
          },
          children: [],
        },
        {
          type: 2,
          name: $t('用户管理'),
          code: '1111111111_auth__user',
          icon: 'carbon-home',
          path: '/user-admin',
          component: '/user-admin/index.vue',
          href: '',
          visible: true,
          // defaultShow: true,
          meta: {
            title: '权限中心-用户管理',
          },
          children: [],
        },
      ],
    }],
    [AppCodeType.CONFIG]: [
      {
        type: 1,
        name: '配置中心',
        code: 'config',
        active: true,
        sort: 2,
        children: [
          {
            type: 2,
            name: $t('首页'),
            code: 'config_home',
            icon: 'carbon-home',
            path: '/home',
            component: '/home/index.vue',
            href: '',
            visible: true,
            meta: {
              title: '配置中心-首页',
            },
            children: [],
          },
          // {
          //   type: 2,
          //   name: $t('用例'),
          //   code: 'config_demo',
          //   icon: 'carbon-home',
          //   // path: '/demo',
          //   // component: '/demo/demo1.vue',
          //   href: '',
          //   visible: true,
          //   // meta: {
          //   //   title: '首页',
          //   // },
          //   children: [
          //     {
          //       type: 2,
          //       name: $t('demo1'),
          //       code: 'config-demo1',
          //       // icon: 'carbon-home',
          //       path: '/demo/1',
          //       component: '/demo/demo1.vue',
          //       href: '',
          //       visible: true,
          //       meta: {
          //         title: 'demo1',
          //       },
          //       children: [],
          //     },
          //     {
          //       type: 2,
          //       name: $t('demo2'),
          //       code: 'config-demo2',
          //       // icon: 'carbon-home',
          //       path: '/demo/2',
          //       component: '/demo/demo2.vue',
          //       href: '',
          //       visible: true,
          //       meta: {
          //         title: 'demo2',
          //       },
          //       children: [],
          //     },
          //   ],
          // },
        ],
      },
    ],
    [AppCodeType.I18N]: [
      {
        type: 1,
        name: '翻译中心',
        code: 'translate',
        active: true,
        sort: 1,
        children: [
          {
            type: 2,
            name: $t('首页'),
            code: 'translate_home',
            icon: 'carbon-home',
            path: '/home',
            component: '/home/index.vue',
            href: '',
            visible: true,
            meta: {
              title: '配置中心-首页',
            },
            children: [],
          },
        ],
      },
    ],
  } as any)[type]
}

export function useInitApp(app: App) {
  function installModules(modules: UseModuleType[], cb?: () => void) {
    Object.values(import.meta.glob('../../modules/*.ts', { eager: true }))
      .forEach((i: any) => {
        const isNeedInstall = modules.includes(i?.moduleType)

        if (isNeedInstall)
          i?.install(app)
      })

    cb?.()
  }

  async function setUserInfo() {

  }

  // async function setConfigInfo() {

  // }

  async function setProjects(list?: any) {
    const projects = await new Promise((resolve) => {
      setTimeout(() => {
        resolve(list || data())
      }, 800)
    }) as any

    const projectStore = useProjectStore()

    function removeFields(obj: Record<string, any>, fields: string[]) {
      return cloneDeep(obj).map((item: any) => {
        return omit(item, fields)
      }).map((item: any) => {
        if (item.children && item.children.length > 0) {
          item.children = removeFields(item.children, fields)
        }
        return item
      })
    }

    if (!isEqual(projects, removeFields(projectStore.getProjects, ['projectCode', 'appCode', 'query']))) {
      projectStore.setProjects(projects)
      // ElMessageBox.alert(
      //   `您可以选择立即刷新？`,
      //   '菜单已更新',
      //   {
      //     confirmButtonText: '立即刷新',
      //     callback: (action: Action) => {
      //       if (action === 'confirm') {
      //         window.location.href = '/'
      //       }
      //     },
      //   },
      // )
    }
  }

  async function setApps(appCode: AppCodeType) {
    const apps = await new Promise((resolve) => {
      setTimeout(() => {
        resolve(getApps(appCode))
      }, 500)
    }) as any

    function removeFields(obj: Record<string, any>, fields: string[]) {
      return cloneDeep(obj).map((item: any) => {
        return omit(item, fields)
      }).map((item: any) => {
        if (item.children && item.children.length > 0) {
          item.children = removeFields(item.children, fields)
        }
        return item
      })
    }

    const appStore = useAppStore()

    if (!isEqual(apps, removeFields(appStore.getApps, ['projectCode', 'appCode', 'query']))) {
      appStore.setApps(apps, appCode)

      // ElMessageBox.alert(
      //   `您可以选择立即刷新？`,
      //   '菜单已更新',
      //   {
      //     confirmButtonText: '立即刷新',
      //     callback: (action: Action) => {
      //       if (action === 'confirm') {
      //         window.location.href = '/'
      //       }
      //     },
      //   },
      // )
    }
  }

  async function setLanguages(language?: string, cb?: () => void) {
    const localeStore = useLocaleStore()
    const paramsLanguage = language || new URLSearchParams(location.search).get('language') as any || localeStore.getLanguage || DEFAULT_LANGUAGE

    localeStore.setLanguage(
      paramsLanguage,
      (language: LanguageType, locale: any) => {
        i18n.global.locale.value = language
        i18n.global.setLocaleMessage(language, locale)

        cb?.()
      },
    )

    return paramsLanguage
  }

  function setTitle(title?: string) {
    useTitle(title || TITLE)
  }

  function setTheme(color?: string) {
    const configStore = useConfigStore()
    const c = color || configStore.getThemeColor || THEME_COLOR
    useToggleTheme(c)

    const html = document.querySelector('html')!
    html.style.filter = `grayscale(${Number(configStore.getIsGreyMode)})`
  }

  function setWritingMode(mode?: WritingMode) {
    const configStore = useConfigStore()
    const m = mode || configStore.getWritingMode || WRITING_MODE

    const html = document.querySelector('html')!
    html.setAttribute('dir', m)
  }

  function setFirstScreenLoading({ title, loadingEle = '.g-loading-container' }: { title: string, isMainApp?: boolean, loadingEle?: string }) {
    const loadingContainer = document.querySelector(loadingEle) as any

    if (loadingContainer) {
      loadingContainer.style.display = 'flex'
    }

    const textEle = document.querySelector(`${loadingEle}__text`) as any
    if (textEle) {
      textEle.innerHTML = title
    }
    const endLoading = () => {
      if (loadingContainer) {
        loadingContainer.style.display = 'none'
      }
    }

    return {
      endLoading,
    }
  }

  function cancelFirstScreenLoading() {
    const loadingContainer = document.querySelector('.g-loading-container') as any
    if (loadingContainer) {
      loadingContainer.style.display = 'none'
    }
  }

  return {
    installModules,
    setUserInfo,
    setLanguages,
    setProjects,
    setApps,
    setTitle,
    setTheme,
    setWritingMode,
    setFirstScreenLoading,
    cancelFirstScreenLoading,
  }
}
